package com.ruoyi.project.zxcrm.controller;


import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.zx.PageData;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.system.domain.SysDictData;
import com.ruoyi.project.system.mapper.SysDictDataMapper;

import com.ruoyi.project.zxcrm.mapper.CrmLeadMapper;
import com.ruoyi.project.zxcrm.service.impl.CrmLeadServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;

/**
 * 订单跟踪Controller
 *
 * @author wenrui
 * @date 2022-12-30
 */
@RestController
@RequestMapping(value = "/crm/lead")
@RequiredArgsConstructor
public class CrmLeadController extends BaseController {
    private final CrmLeadServiceImpl CrmLeadService;

    private final CrmLeadMapper crmLeadMapper;

    private final SysDictDataMapper sysDictDataMapper;

    /**
     * 查询订单跟踪列表
     */
    @PreAuthorize("@ss.hasPermi('crm:lead:list')")
    @GetMapping("/list")
    public TableDataInfo list() {
        PageData pd = this.getPageData();
        startPage();
        List<PageData> list = CrmLeadService.selectCrmLeadList(pd);
        return getDataTable(list);
    }

    /**
     * 导出订单跟踪列表
     */
    @PreAuthorize("@ss.hasPermi('crm:lead:export')")
    @Log(title = "订单跟踪", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, PageData pd) {
        List<PageData> list = CrmLeadService.selectCrmLeadList(pd);
        ExcelUtil<PageData> util = new ExcelUtil<PageData>(PageData.class);
        util.exportExcel(response, list, "订单跟踪数据");
    }

    /**
     * 获取订单跟踪详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(CrmLeadService.selectCrmLeadById(id));
    }

    /**
     * 新增订单跟踪

    @PreAuthorize("@ss.hasPermi('crm:lead:add')")
    @Log(title = "订单跟踪", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CrmLead crmLead) {
        return toAjax(CrmLeadService.insertCrmLead(crmLead));
    }
     */

    /**
     * 修改订单跟踪
     */
    @PreAuthorize("@ss.hasPermi('crm:lead:edit')")
    @Log(title = "订单跟踪", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody PageData pd) {
        pd.put("crm_state",pd.get("state"));
        CrmLeadService.insertLeadComment(pd);
        return toAjax(CrmLeadService.updateCrmLead(pd));
    }

    /**
     * 删除订单跟踪
     */
    @PreAuthorize("@ss.hasPermi('crm:lead:remove')")
    @Log(title = "订单跟踪", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(CrmLeadService.deleteCrmLeadByIds(ids));
    }

    /**
     * 查询跟进记录列表
     */

    @GetMapping("/commentList")
    public AjaxResult commentList() {
        PageData pd = this.getPageData();
        List<PageData> list = CrmLeadService.selectCrmLeadCommentList(pd);
        SysDictData dictData = new SysDictData();
        dictData.setDictType("customer_state");
        List<SysDictData> crm_product = sysDictDataMapper.selectDictDataByType(dictData);
        list.stream().forEach(a -> {
            Object crm_state = a.get("crm_state");
            if (crm_state != null) {
                crm_product.stream().forEach(b -> {
                    if (a.get("crm_state").equals(b.getDictValue())) {
                        a.put("crm_state", b.getDictLabel());
                    }
                });

            }
        });
        return AjaxResult.success("list", list);
    }

    /**
     * 新增跟进记录
     */
    @Log(title = "跟进记录", businessType = BusinessType.INSERT)
    @PostMapping(value = "/commentAdd")
    public AjaxResult commentAdd(@RequestBody PageData pd) {

        pd.put("create_by", this.getUsername());
        pd.put("create_time", DateUtils.getNowDate());
        pd.put("tenant_id", this.getUserTenantId());
        CrmLeadService.insertLeadComment(pd);

        Date nextTime;
        if (pd.get("nextFollowupTime") == null) {
            nextTime = DateUtils.addDays(DateUtils.getNowDate(), 1);
        } else {
            nextTime = DateUtils.dateTime("yyyy-MM-dd", pd.getString("nextFollowupTime"));
        }
        pd.put("next_time",nextTime);
//        crmLead.setRemark(pd.getString("remark"));
        CrmLeadService.updateCrmLead(pd);

        return AjaxResult.success();
    }

    @PreAuthorize("@ss.hasPermi('bd:partner:privilege')")
    @Log(title = "权限归属客户", businessType = BusinessType.UPDATE)
    @PutMapping("/{ids}/{user_id}")
    public AjaxResult privilegeSalas(@PathVariable Long[] ids, @PathVariable Long user_id) {
        return toAjax(crmLeadMapper.updateUserId(ids, user_id));
    }

    @GetMapping("/LeadTime/{id}")
    public TableDataInfo queryLeadTime(@PathVariable Long id) {
        startPage();
        List<PageData> list = crmLeadMapper.queryLeadTime(id);
        return getDataTable(list);
    }

}
